package com.lottery.im.module.result.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ListView;
import android.widget.RelativeLayout;
import butterknife.BindView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.lottery.im.R;
import com.lottery.im.api.Api;
import com.lottery.im.api.result.entity.AdInfo;
import com.lottery.im.api.result.entity.BannerInfo;
import com.lottery.im.api.result.entity.ResultInfo;
import com.lottery.im.base.BaseSwipeFragment;
import com.lottery.im.common.WeakReferenceHandler;
import com.lottery.im.constant.Constants;
import com.lottery.im.constant.RxBusCode;
import com.lottery.im.module.main.ui.AgentWebViewActivity;
import com.lottery.im.module.result.adapter.result.MainResultAdapter;
import com.lottery.im.module.result.presenter.ResultPresenter;
import com.lottery.im.module.result.ui.game.Game28Fragment;
import com.lottery.im.module.result.ui.game.GameFastFragment;
import com.lottery.im.module.result.ui.game.GameLotteryFragment;
import com.lottery.im.module.result.ui.game.GamePkFragment;
import com.lottery.im.module.result.view.ResultView;
import com.lottery.im.util.ScreenUtils;
import com.lottery.im.util.rxbus.RxBus;
import com.lottery.im.util.rxbus.Subscribe;
import com.lottery.im.view.RoundedImageView;
import com.lottery.im.widget.banner.ConvenientBanner;
import com.lottery.im.widget.banner.holder.Holder;
import com.lottery.im.widget.banner.transformer.ScaleInTransformer;
import com.lottery.im.widget.banner.view.CBLoopViewPager;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class ResultFragment extends BaseSwipeFragment<ResultPresenter> implements ResultView,
    MainResultAdapter.Callback {
  @BindView(R.id.refreshLayout) RefreshLayout mRefreshLayout;
  @BindView(R.id.result_list) ListView mListView;
  private View mHeaderView;
  private ConvenientBanner mConvenientBanner;
  private List<BannerInfo> mBannerList = new ArrayList<>();
  private int[] mIndicators = {
      R.drawable.ic_result_banner_indicator, R.drawable.ic_result_banner_indicator_focused
  };
  private List<ResultInfo> mResultList = new ArrayList<>();
  private MainResultAdapter mAdapter;
  private boolean isQuery;
  private MyHandler mHandler;
  private Timer timer;

  @SuppressLint("HandlerLeak")
  private class MyHandler extends WeakReferenceHandler<BaseSwipeFragment> {
    public MyHandler(BaseSwipeFragment reference) {
      super(reference);
    }

    protected void handleMessage(BaseSwipeFragment reference, Message msg) {
      switch (msg.what) {
        case 0:
          if (null == mActivity || mActivity.isFinishing()) {
            return;
          }
          if (!isQuery) {//避免同一时间重复请求
            isQuery = true;
            presenter.queryAllGameTypeResult();
          }
          break;
      }
    }
  }

  @Override protected int getLayoutResId() {
    return R.layout.fragment_result;
  }

  @Override protected void initPresenter() {
    presenter = new ResultPresenter(getActivity(), this, this);
    presenter.init();
  }

  @Override public void initView() {
    RxBus.get().register(this);
    mAdapter = new MainResultAdapter(getActivity(), mResultList, this);
    mListView.setAdapter(mAdapter);
    mListView.addHeaderView(getHeaderView());
    mRefreshLayout.setEnableLoadMore(false);
    mRefreshLayout.setOnRefreshListener(refreshLayout -> {
      refreshLayout.finishRefresh(0);
      refresh();
    });
    presenter.getAd();
    presenter.queryAllGameTypeResult();
    mHandler = new MyHandler(this);
    timer = new Timer();
    timer.schedule(new TimerTask() {
      @Override
      public void run() {
        if (mHandler != null) {
          Message message = mHandler.obtainMessage(0);
          mHandler.handleMessage(message);
        }
      }
    }, 0, 5000);
  }

  @Override public void itemClick(int position) {
    String gameType = mResultList.get(position).getGameType();
    if (Constants.lotteryArr.contains(gameType) || Constants.sd115Arr.contains(gameType)) {
      startFragment(GameLotteryFragment.create(gameType,
          mResultList.get(position).getGameName()));
    } else if (Constants.pkArr.contains(gameType)) {
      startFragment(GamePkFragment.create(gameType,
          mResultList.get(position).getGameName()));
    } else if (Constants.fastArr.contains(gameType)) {
      startFragment(GameFastFragment.create(gameType,
          mResultList.get(position).getGameName()));
    } else if (Constants.bj28Arr.contains(gameType)) {
      startFragment(Game28Fragment.create(gameType,
          mResultList.get(position).getGameName()));
    }
  }

  @Override protected boolean canDragBack() {
    return false;
  }

  /*
   * 头部 banner + 长龙统计
   * */
  private View getHeaderView() {
    if (null == mHeaderView) {
      mHeaderView = getLayoutInflater().inflate(R.layout.header_result_list, null);
      mConvenientBanner = mHeaderView.findViewById(R.id.result_banner);
      mHeaderView.findViewById(R.id.result_statistics)
          .setOnClickListener(v -> startFragment(new LongDragonFragment()));
    }
    return mHeaderView;
  }

  @Override public void getAdSuccess(AdInfo adInfo) {
    mBannerList.clear();
    if (null != adInfo && null != adInfo.getBannerList() && adInfo.getBannerList().size() > 0) {
      mBannerList.addAll(adInfo.getBannerList());
    }
    initBanner();
  }

  @Override public void querySuccess(List<ResultInfo> list) {
    isQuery = false;
    mResultList.clear();
    for (int i = 0; i < list.size(); i++) {
      ResultInfo info = list.get(i);
      String gameType = info.getGameType();
      String resultStr = info.getResultStr();
      String issueId = info.getIssueId();
      info.setIsSueId(
          issueId.length() >= 3 ? issueId.substring(issueId.length() - 3, issueId.length()) + "期"
              : issueId + "期");
      if (Constants.lotteryArr.contains(gameType)) {
        if (resultStr.length() > 0) {
          String[] str = resultStr.split(",");
          if (str.length >= 5) {
            info.setStringStr(Arrays.asList(str));
            int w = Integer.parseInt(str[0]);
            int q = Integer.parseInt(str[1]);
            int b = Integer.parseInt(str[2]);
            int s = Integer.parseInt(str[3]);
            int g = Integer.parseInt(str[4]);
            int sum = w + q + b + s + g;
            String lh;
            String dx;
            String ds;
            if (w > g) {
              lh = "龙";
            } else if (w < g) {
              lh = "虎";
            } else {
              lh = "和";
            }
            if (sum >= 23) {
              dx = "大";
            } else {
              dx = "小";
            }
            if (sum % 2 == 0) {
              ds = "双";
            } else {
              ds = "单";
            }
            info.setLongHu(lh);
            info.setHeZhi(sum + "    " + dx + "    " + ds);
          }
        }
      }
      if (Constants.fastArr.contains(gameType)) {
        if (resultStr.length() > 0) {
          String[] str = resultStr.split(",");
          if (str.length >= 3) {
            info.setStringStr(Arrays.asList(str));
            int w = Integer.parseInt(str[0]);
            int q = Integer.parseInt(str[1]);
            int b = Integer.parseInt(str[2]);
            int sum = w + q + b;
            String dx;
            String ds;
            if (sum > 10) {
              dx = "大";
            } else {
              dx = "小";
            }
            if (sum % 2 == 0) {
              ds = "双";
            } else {
              ds = "单";
            }
            info.setHeZhi(sum + "    " + dx + "    " + ds);
          }
        }
      }
      if (Constants.pkArr.contains(gameType)) {
        if (resultStr.length() > 0) {
          String[] str = resultStr.split(",");
          if (str.length >= 10) {
            info.setStringStr(Arrays.asList(str));
            int a1 = Integer.parseInt(str[0]);
            int a2 = Integer.parseInt(str[1]);
            int a3 = Integer.parseInt(str[2]);
            int a4 = Integer.parseInt(str[3]);
            int a5 = Integer.parseInt(str[4]);
            int a6 = Integer.parseInt(str[5]);
            int a7 = Integer.parseInt(str[6]);
            int a8 = Integer.parseInt(str[7]);
            int a9 = Integer.parseInt(str[8]);
            int a10 = Integer.parseInt(str[9]);
            int sum = a1 + a2;
            String lh1;
            String lh2;
            String lh3;
            String lh4;
            String lh5;
            String dx;
            String ds;
            if (a1 > a10) {
              lh1 = "龙";
            } else {
              lh1 = "虎";
            }
            if (a2 > a9) {
              lh2 = "龙";
            } else {
              lh2 = "虎";
            }
            if (a3 > a8) {
              lh3 = "龙";
            } else {
              lh3 = "虎";
            }
            if (a4 > a7) {
              lh4 = "龙";
            } else {
              lh4 = "虎";
            }
            if (a5 > a6) {
              lh5 = "龙";
            } else {
              lh5 = "虎";
            }
            if (sum > 11) {
              dx = "大";
            } else {
              dx = "小";
            }
            if (sum % 2 == 0) {
              ds = "双";
            } else {
              ds = "单";
            }
            info.setLongHu(lh1 + "    " + lh2 + "    " + lh3 + "    " + lh4 + "    " + lh5);
            info.setHeZhi(sum + "    " + dx + "    " + ds);
          }
        }
      }
      if (Constants.sd115Arr.contains(gameType)) {
        if (resultStr.length() > 0) {
          String[] str = resultStr.split(",");
          if (str.length >= 5) {
            info.setStringStr(Arrays.asList(str));
            int w = Integer.parseInt(str[0]);
            int q = Integer.parseInt(str[1]);
            int b = Integer.parseInt(str[2]);
            int s = Integer.parseInt(str[3]);
            int g = Integer.parseInt(str[4]);
            int sum = w + q + b + s + g;
            String lh;
            String dx;
            String ds;
            if (w > g) {
              lh = "龙";
            } else if (w < g) {
              lh = "虎";
            } else {
              lh = "和";
            }
            if (sum == 30) {
              dx = "中";
            } else if (sum > 30) {
              dx = "大";
            } else {
              dx = "小";
            }
            if (sum % 2 == 0) {
              ds = "双";
            } else {
              ds = "单";
            }
            info.setLongHu(lh);
            info.setHeZhi(sum + "    " + dx + "    " + ds);
          }
        }
      }
      if (Constants.bj28Arr.contains(gameType)) {
        if (resultStr.length() > 0) {
          String[] str = resultStr.split(",");
          if (str.length >= 3) {
            info.setStringStr(Arrays.asList(str));
            int w = Integer.parseInt(str[0]);
            int q = Integer.parseInt(str[1]);
            int b = Integer.parseInt(str[2]);
            int sum = w + q + b;
            String dx;
            String ds;
            if (sum >= 14) {
              dx = "大";
            } else {
              dx = "小";
            }
            if (sum % 2 == 0) {
              ds = "双";
            } else {
              ds = "单";
            }
            info.setHeZhi(sum + "    " + dx + "    " + ds);
          }
        }
      }
    }
    mResultList.addAll(list);
    mAdapter.notifyDataSetChanged();
  }

  private void initBanner() {
    mConvenientBanner.setPages(NetworkImageHolderView::new, mBannerList)
        .setPageIndicator(mIndicators)
        .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL);
    mConvenientBanner.startTurning(3000);
    CBLoopViewPager viewPager = mConvenientBanner.getViewPager();
    viewPager.setPageMargin(20);
    viewPager.setOffscreenPageLimit(3);
    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewPager.getLayoutParams();
    int left = ScreenUtils.dp2px(getActivity(), 20f);
    params.setMargins(left, 0, left, 0);
    mConvenientBanner.setPageTransformer(new ScaleInTransformer());
    mConvenientBanner.setOnSimpleItemClickListener(position -> {
      String url = mBannerList.get(position).getUrl();
      String name = mBannerList.get(position).getName();
      if (!TextUtils.isEmpty(url)) {
        AgentWebViewActivity.create(this, url, name);
      }
    });
  }

  @SuppressLint("InflateParams")
  public class NetworkImageHolderView implements Holder<BannerInfo> {
    RoundedImageView imageView;

    @Override
    public View createView(Context context) {
      View v = LayoutInflater.from(getActivity()).inflate(R.layout.item_banner_card, null);
      imageView = v.findViewById(R.id.item_img);
      return v;
    }

    @Override
    public void UpdateUI(Context context, int position, BannerInfo data) {
      Glide.with(context)
          .load(Api.BASEADDRESS + data.getImageUrl())
          .apply(RequestOptions.fitCenterTransform()
              //.error(R.drawable.img_error_banner)
              .diskCacheStrategy(DiskCacheStrategy.ALL))
          .into(imageView);
    }
  }

  /*
   * 刷新彩种预测结果
   * */
  @Subscribe(code = RxBusCode.COUNT_DOWN_CODE)
  public void refresh() {
    if (null == mActivity || mActivity.isFinishing()) {
      return;
    }
    if (!isQuery) {//避免同一时间重复请求
      isQuery = true;
      presenter.queryAllGameTypeResult();
    }
  }

  @Subscribe(code = RxBusCode.ONRESUME_CODE)
  public void refreshOnResume() {
    presenter.queryAllGameTypeResult();
  }

  @Override public void onDestroy() {
    super.onDestroy();
    RxBus.get().unRegister(this);
  }
}
